package com.strato.i18n.v1_0_0;

import java.text.MessageFormat;
import java.util.Collection;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import com.strato.i18n.v1_0_0.activator.Activator;

public class Messages {

	private static Messages instance=new Messages();
	
	public static Messages getInstance() {
		return instance;
	}

	public static String DEFAULT_LOCALE="";

	public String getMessage(String key,Object... args){
		return getMessage(null,key,args);
	}
	public String getMessage(Locale locale,String key,Object... args){
		if(locale==null){
			locale=LocaleContext.get();
		}
		String localeName=DEFAULT_LOCALE;
		if(locale!=null){
			localeName=locale.toLanguageTag();
		}
		Map<String, Map<String, Properties>> resources = Activator.getDiscover().getResources();
		String foundMessage=null;
		for(Map<String, Properties> map:resources.values()){
			Properties p=map.get(localeName);
			if(p!=null&&p.containsKey(key)){
				foundMessage=p.getProperty(key);
				break;
			}
			p=map.get(DEFAULT_LOCALE);
			if(p!=null&&p.containsKey(key)){
				foundMessage=p.getProperty(key);
				break;
			}
		}
		if(foundMessage==null){
			if(args==null||args.length==0){
				return key;
			}else{
				StringBuffer buf=new StringBuffer();
				buf.append(key).append("[");
				for(int i=0;i<args.length;i++){
					buf.append(args[i]);
					if(i<args.length-1){
						buf.append(",");
					}
				}
				buf.append("]");
				return buf.toString();
			}
		}else{
			return MessageFormat.format(foundMessage, args);
		}
	}

	public Collection<String> getAvailableLocales(){
		return Activator.getDiscover().getLocales();
	}
	
	public Collection<String> getKeys(Locale locale){
		if(locale==null){
			locale=LocaleContext.get();
		}
		String localeName=DEFAULT_LOCALE;
		if(locale!=null){
			localeName=locale.toLanguageTag();
		}
		Map<String, Map<String, Properties>> resources = Activator.getDiscover().getResources();
		Set<String> keys=new HashSet<>();
		for(Map<String, Properties> map:resources.values()){
			Properties p=map.get(localeName);
			if(p==null){
				p=map.get(DEFAULT_LOCALE);
			}
			if(p!=null){
				Set<Object> pKeys = p.keySet();
				for(Object key:pKeys){
					keys.add((String)key);
				}
			}
		}
		return keys;
	}
	
	public void setLocale(String localeName){
		Locale locale = Locale.forLanguageTag(localeName);
		LocaleContext.set(locale);
	}
}
